package org.truenewx.tnxjee.model.spec.menu;

import java.util.Collections;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

/**
 * 菜单
 *
 * @author jianglei
 */
public class Menu implements Comparable<Menu> {

    private String name;
    private String caption;
    private MenuItem[] items;
    private int ordinal;

    public Menu() {
    }

    public Menu(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCaption() {
        return this.caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public MenuItem[] getItems() {
        return this.items;
    }

    public void setItems(MenuItem[] items) {
        this.items = items;
    }

    public int getOrdinal() {
        return this.ordinal;
    }

    public void setOrdinal(int ordinal) {
        this.ordinal = ordinal;
    }

    @Override
    public int compareTo(Menu other) {
        int result = Integer.compare(this.ordinal, other.ordinal);
        if (result == 0) {
            result = this.name.compareTo(other.name);
        }
        return result;
    }

    public List<MenuItem> getItemChainByPermission(String permission) {
        if (this.items != null) {
            for (MenuItem item : this.items) {
                List<MenuItem> chain = item.getChainByPermission(permission);
                if (CollectionUtils.isNotEmpty(chain)) {
                    return chain;
                }
            }
        }
        return Collections.emptyList();
    }

    public Menu cloneWithoutItems() {
        Menu menu = new Menu(getName());
        menu.setCaption(getCaption());
        menu.setOrdinal(getOrdinal());
        return menu;
    }

}
